<template>

  <div style="padding: 20px;">
    <!--  页面的搜索表单 -->
    <div>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="品牌名称">
          <el-input v-model="queryParams.searchValue" placeholder="请输入品牌名称" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="initPageData">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  增删改按钮组 -->
    <div>
      <el-button type="primary" plain :icon="Plus" @click="handleShowSaveDialog"
                 v-hasPermi="['product:brand:add']">新增</el-button>
      <el-button type="success" plain    v-hasPermi="['product:brand:edit']" :icon="Edit">修改</el-button>
      <el-button type="danger" plain :icon="Delete" v-hasPermi="['product:brand:del']" @click="handleBatchDel">批量删除</el-button>
    </div>
    <!--    品牌列表 -->
    <div>
      <el-table @selection-change="handleSelectChange" :data="list" stripe style="width: 100%;margin-top: 10px;">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="品牌名称">
        </el-table-column>
        <el-table-column prop="logo" label="品牌图标">
          <template #default="scope">
            <img :src="scope.row.logo" alt="" style="width: 40px;height: 40px;">
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small"
                       v-hasPermi="['product:brand:edit']"
                       @click="handleShowEditDialog(scope.row)">
              修改
            </el-button>
            <el-button link type="primary" size="small"
                       v-hasPermi="['product:brand:del']"
                       @click="handleDelBrand(scope.row.name,scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页导航 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="initPageData"
      />
    </div>

    <!--    新增/更新对话框 -->
    <div>
      <el-dialog v-model="saveDialogFormVisible" :title="title" width="500">
        <el-form>
          <el-form-item label="品牌名称" :label-width="formLabelWidth">
            <el-input v-model="brand.name" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="品牌图标" :label-width="formLabelWidth">
            <el-upload
                class="avatar-uploader"
                :action="uploadPath"
                :show-file-list="false"
                :headers="{'Authorization': 'Bearer ' + getToken()}"
                :on-success="handleUploadSuccess"
            >
              <img v-if="brand.logo" :src="brand.logo" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="saveDialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdate"  v-hasPermi="['product:brand:add','product:brand:edit']">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>

</template>

<script setup>
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import {listBrands, delBrand,saveBrand , getBrandById , updateBrand} from '@/api/product/brand.js'
import {ElMessage, ElMessageBox} from "element-plus";
import { getToken } from '@/utils/auth' //用户登录token的工具
//1、查询页面数据：
// 页面初始化时发起异步请求加载品牌分页列表
onMounted(() => {
  initPageData()
})
//加载数据的函数：同步阻塞执行
const initPageData = async () => {
  //  异步请求 ，从返回的对象中获取它的code  rows和total三个属性值
  const {rows, total: t} = await listBrands(queryParams.value)
  //list接收查询到的分页列表
  list.value = rows; //使用响应式对象的value接收数据
  total.value = t;
}
//分页列表数据
const list = ref([])
const total = ref(100)
const queryParams = ref({
  pageNum: 1,
  pageSize: 3,
  searchValue: null
})
//重置按钮事件函数
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 3,
    searchValue: null
  }
  initPageData()
}
//2、删除品牌
const handleDelBrand = (name, ids) => {
  //弹出确认删除的提示
  ElMessageBox.confirm(
      `正在删除品牌 ${name},是否继续?`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await delBrand(ids)
        ElMessage.success("删除成功")
        //刷新页面数据
        initPageData();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}
//3、批量删除品牌
const handleBatchDel = () => {
  //1、判断是否选中了要删除的记录
  if (!selectRows.value || selectRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }
  //2、获取选中记录的id列表 拼接为 逗号分割的字符串
  let ids = selectRows.value.map(row => row.id).join(',')
  let names = selectRows.value.map(row => row.name).join('、')
  // console.log(ids)
  //3、调用上面的函数删除
  handleDelBrand(names, ids)
  // ElMessageBox.confirm(
  //     `正在批量删除选中的品牌 ${names},是否继续?`,
  //     '删除确认',
  //     {
  //       confirmButtonText: '确认',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     }
  // )
  //     .then(async () => {
  //       await delBrand(ids)
  //       ElMessage.success("删除成功")
  //       //刷新页面数据
  //       initPageData();
  //     })
  //     .catch(() => {
  //       ElMessage({
  //         type: 'info',
  //         message: '取消删除',
  //       })
  //     })

}
//4、表格的行选中状态变化时的回调
const selectRows = ref([]) //接收选中要删除行的变量
const handleSelectChange = (newSelection) => {
  // console.log('表格选中行变化了：',newSelection)
  selectRows.value = newSelection;
}

//5、新增按钮事件函数： 弹出新增对话框
const handleShowSaveDialog = () => {
  title.value = '新增品牌'
  //解决缓存问题
  brand.value = {}
  saveDialogFormVisible.value = true
}
const saveDialogFormVisible = ref(false)
const formLabelWidth = ref('120px')
const brand = ref({}) //新增对话框接收新增数据的对象
const title = ref('新增品牌') //对话框标题
//===上传组件的属性 和函数
const uploadPath = 'http://localhost:8080/file/upload'
const handleUploadSuccess = (r)=>{//r表示上传成功的结果，上传的响应报文状态码为200时回调
  //如果响应体 对象的code值也是200表示成功
  if(r.code === 200){
    brand.value.logo = r.data.url
    ElMessage.success('文件上传成功')
  }else{
    ElMessage.error('文件上传失败，网络错误')
  }


}
//====上传组件  end======

//6、对话框提交按钮事件函数： 提交品牌数据保存
const handleSave = async ()=>{
  await saveBrand(brand.value)
  ElMessage.success('新增成功')
  initPageData()
  //关闭对话框
  saveDialogFormVisible.value = false
}
//7、修改按钮事件函数：  查询要修改的品牌信息 弹出对话框展示
const handleShowEditDialog = async (row)=>{
  //查询要修改的品牌
  title.value = '更新品牌'
  const {data} = await getBrandById(row.id)
  brand.value = data //使用新增修改对话框绑定的变量接收 查询到的品牌
  //弹出对话框
  saveDialogFormVisible.value = true
}
//8、提交修改请求
const handleUpdate = async  ()=>{
  await updateBrand(brand.value)
  initPageData()
  ElMessage.success('更新成功')
  saveDialogFormVisible.value = false
}
//9、新增、更新对话框 提交按钮的事件函数
const handleSaveOrUpdate = ()=>{
  if(brand.value.id){
    //更新
    handleUpdate()
  }else{
    //新增
    handleSave()
  }
}
</script>

<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>